package foodserver;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.subway.babynote.syncdata.ClientDataRecordBase;
import com.subway.babynote.syncdata.PostParam;


import querysrc.query;
import querysrc.query_authenticate;
import querysrc.query_food_prop;
import querysrc.sqlConnectionHandler;
import querysrc.sqlConnectionHandlerManager;
import serverdata.httpreqhandler;

/**
 * Servlet implementation class abc
 */
public class abc extends HttpServlet {
	private static final long serialVersionUID = 1L;
	query_food_prop qa = null;
	protected sqlConnectionHandler sqlconhandler = null;	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public abc() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init()throws ServletException 
	{
	    try {
	    	sqlconhandler = sqlConnectionHandlerManager.getHandler();
	    	qa = new query_food_prop(this.sqlconhandler);
	      }
	      catch (Exception se) {
	        System.out.println("Exception: "+se.getMessage());
	        se.printStackTrace();
	      }
	}

	
	protected void release_query(query q)
	{
		if(q != null)
		{
			q.finalize();
			q = null;
		}
	}
	
	public void destroy () {
		    try {
		    	sqlconhandler = null;
		    	this.release_query(qa);
		    	
		    }     
		    catch (Exception e) {
		      e.printStackTrace();
		    }      
	
	 }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		JSONArray jsona = new JSONArray();
		 List<ClientDataRecordBase> al= qa.get_food_prop(0);
		 Iterator<ClientDataRecordBase> it = al.iterator();
		 while (it.hasNext())
		 {
			 ClientDataRecordBase cdrb = it.next();
			 JSONObject tempjsono =  cdrb.toJSON();
			 jsona.put(tempjsono);
		 }		
		 JSONObject return_value = new JSONObject();
		 try {
			return_value.put(PostParam.ReturnValue_Param.return_status, 0);
		
			return_value.put(PostParam.last_avgRecord_Param.records, jsona);
		 } catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 //return_value.put(PostParam.ReturnValue_Param.err_message, errMessage.err_authenfail.errcode);
		 httpreqhandler.writeOutput(return_value, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
